// 📦 引入工具库
const _ = require("lodash");
const path = require("path");
const fs = require("fs");

// 📦 ESM 支持模块加载
const esm = require("esm");
const requireModule = esm(module);

// 📦 项目依赖模块
const { readAllValues } = requireModule(
  "../../../awakened-potential/helpers/readAllValues.js"
);
const checkAccuracy = requireModule("../../utils/checkAccuracy.js");

// ✅ 读取历史开奖数据（模拟全部）
const allValues = readAllValues("m");

// ✅ 号码池（01 ~ 49）
const allNumbers = Array.from({ length: 49 }, (_, i) =>
  (i + 1).toString().padStart(2, "0")
);

// ✅ 是否使用窗口
const useWindow = true;
// ✅ 窗口大小
const windowSize = 5;

// ✅ 存储预测结果
const predictResults = [];
let correct = 0;
let maxWrongStreak = 0;
let currentWrongStreak = 0;

/**
 * 根据窗口内遗漏次数最少策略选出 32 个号码
 */
const select32ByLeastOmission = (temp) => {
  const appeared = new Set(temp.map((item) => item.number));
  const omissionCount = {};

  // 初始化为0
  allNumbers.forEach((num) => {
    omissionCount[num] = 0;
  });

  // 从窗口前向后统计每期遗漏次数
  for (let i = 0; i < temp.length; i++) {
    const number = temp[i].number;
    allNumbers.forEach((n) => {
      if (n !== number) omissionCount[n] += 1;
    });
  }

  // 得到遗漏次数最少的前 32 个号码
  const sorted = Object.entries(omissionCount)
    .sort((a, b) => a[1] - b[1] || a[0].localeCompare(b[0])) // 少的排前面
    .map(([num]) => num)
    .slice(0, 32);

  if (sorted.length !== 32) {
    throw new Error(`❗ 无法生成 32 个不重复号码（目前只有 ${sorted.length} 个）`);
  }

  return sorted;
};

// ✅ 主循环
allValues.forEach((item, index) => {
  const temp = useWindow
    ? allValues.slice(Math.max(0, index - windowSize), index)
    : allValues.slice(0, index);

  if (temp.length === 0) return;

  const selectedNumbers = select32ByLeastOmission(temp);

  try {
    const isHit = checkAccuracy(selectedNumbers, item.number);
    if (isHit) {
      correct += 1;
      currentWrongStreak = 0;
    } else {
      currentWrongStreak += 1;
      maxWrongStreak = Math.max(maxWrongStreak, currentWrongStreak);
    }
    predictResults.push(selectedNumbers);
  } catch (err) {
    console.error(`❌ checkAccuracy error at index ${index}: ${err.message}`);
  }
});

// ✅ 输出统计结果
const total = predictResults.length;
const accuracy = total > 0 ? ((correct / total) * 100).toFixed(2) : 0;

console.log(`预测总数: ${total}`);
console.log(`命中次数: ${correct}`);
console.log(`准确率: ${accuracy}%`);
console.log(`最大连续错误次数: ${maxWrongStreak}`);
